package com.mydemo.springlearning.functions.encrypt;

import java.util.Base64;

/**
 * 加密手段：
 * 1.对每个字符串字符加补偿值
 * 2.字符串得到字节数组
 * 3.然后base64加密得到字符串
 * 4.然后反转
 */
public class Encryption {
	
	// 加密和解密只要offset一致即可
	public static final int offset = Integer.MIN_VALUE ;
	
	// 加密
	public static String encryption(String inputString) {
		
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < inputString.length(); i++) {
			sb.append("" + (char)(((int)inputString.charAt(i)) + offset));
		}
		String encodeToString = Base64.getEncoder().encodeToString(sb.toString().getBytes());
		return new StringBuilder(encodeToString).reverse().toString();
	}
	
	// 解密
	public static String decryption(String encryptedString) {
		
		encryptedString = new String(Base64.getDecoder().decode(new StringBuilder(encryptedString).reverse().toString()));
		
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < encryptedString.length(); i++) {
			sb.append((char)(((int)encryptedString.charAt(i)) - offset));
		}
		
		return sb.toString();
	}

	public static void main(String[] args) {
		String str = "加密字符串";
        // 使用的时候可嵌套多层，嵌套越多密文越长
		System.out.println(encryption(encryption(str)));
		System.out.println(decryption(decryption(encryption(encryption(str)))));
		System.out.println(decryption("=kWZ3VHa"));
	}
}